#include "devicesync.h"

DeviceSync::DeviceSync(QObject *parent) :
    QObject(parent)
{
    serv = new QTcpServer;

    if (!serv->listen())
    {
        qDebug() << "Error starting server";
    }
    connect(serv, SIGNAL(newConnection()), this, SLOT(handleConnection()));
}

void DeviceSync::setXmlInt(XMLInterface *xmlint)
{
    xml = xmlint;
}

/**
  Handle new client connection.
  */
void DeviceSync::handleConnection()
{
    QTcpSocket *sock = serv->nextPendingConnection();
    connect(sock, SIGNAL(disconnected()), this, SLOT(clientDisconnect()));
    clients.push_back(sock);

    // start pulling data from the device.
    // once that is done, do nothing until user wants to sync device
}

void DeviceSync::getClientData(QTcpSocket *sock)
{
    //sock->write()
}

void DeviceSync::sendToClient()
{
    xml->buildXML("/home/matt/test.xml");
    for (unsigned int k = 0; k < clients.size(); k++)
    {
        QFile xmlFile("/home/matt/test.xml");
        xmlFile.open(QIODevice::ReadOnly);
    }
}

/**
  Client has disconnected, remove from clients list and delete the pointer
  */
void DeviceSync::clientDisconnect()
{
    QTcpSocket *sock = (QTcpSocket *)QObject::sender();
    for (unsigned int k = 0; k < clients.size(); k++)
    {
        if (clients[k] == sock)
        {
            clients.erase(clients.begin()+k);
            return;
        }
    }
}
